package cn.xaut.剑指offer.m20;

// 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

import java.util.Arrays;

public class demo21 {

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
    // 方法1
    public int[] exchange(int[] nums) {

        if (nums.length == 0)
            return nums;
        
        int i = 0, j = nums.length - 1;

        while (true) {
            if (nums[i] % 2 != 0)
                i ++;
            if (nums[j] % 2 == 0)
                j --;
            if (i >= j)
                break;
            // swap(nums[i], nums[j]) 
            swap(nums, i, j);
        }
            
        return nums;
    }


    // 方法2 错误
    public int[] exchange2(int[] nums) {

        if (nums.length == 0)
            return nums;
        
        int m = nums.length / 2;
        int j = m;
        int i = 0;
        while (true) {
            if (nums[i] % 2 != 0)
                i ++;
            if (nums[j] % 2 == 0)
                j ++;
            if (i >= j || i >= m || j >= nums.length)
                break;

            swap(nums, i, j);
        }
        
        return nums;
    }
    
    
    public static void main(String[] args) {

        int[] nums = {1, 2, 3, 4};
        System.out.println(Arrays.toString(new demo21().exchange2(nums)));
    }
}
